package com.demo.kits;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import jodd.io.FileUtil;
import jodd.util.ClassLoaderUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;

/**
 * 汽车之家查违章调用
 * 
 * @author Administrator
 *
 */
public class CarFamilyKit {
	// 查询支持城市url
	private static final String CITY_SUPPORT_URL = "http://open.wz.qichecdn.com/city/GetAllCity?platform_id=17";

	// 查询违章url
	private static final String VIOLATION_URL = "http://open.wz.qichecdn.com/violaton/GetViolation";

	/**
	 * 查询违章
	 * 
	 * @param params
	 * @return
	 */
	public final static String queryViolations(Map<String, String> params) {
		boolean useMock = PropKit.getBoolean("useMock", false);
		if (useMock) {
			return mockData();
		} else {
			final String resData = HttpKit.post(VIOLATION_URL, params, "");
			return resData;
		}
	}

	/**
	 * 查询城市 缓存城市名称
	 * 
	 */
	public final static String queryAllCities() {
		final String cities = HttpKit.get(CITY_SUPPORT_URL);
		return cities;
	}

	/**
	 * 
	 * 根据城市名称找城市id
	 * 
	 * @param city_name
	 * @return
	 * @throws IOException
	 */
	public static String queryCityIdByName(final String cname) {
		// 缓存过期查询城市
		// final String allCities = queryAllCities();
		String allCities = null;
		try {
			allCities = FileUtil.readString(ClassLoaderUtil
					.getResourceFile("/cities.txt"));
			final JSONObject allObj = JSON.parseObject(allCities);
			final JSONArray cityItems = allObj.getJSONObject("result")
					.getJSONArray("items");
			Iterator<Object> iter = cityItems.iterator();
			while (iter.hasNext()) {
				JSONObject item = (JSONObject) iter.next();
				final String cityname = item.getString("cityname");
				if (cityname.equalsIgnoreCase(cname)) {
					return "" + item.getIntValue("cityid");
				}
			}
		} catch (Exception exc) {
			System.out.println(exc);
		}

		return "";
	}

	public final static String mockData() {
		String ret = "";
		try {
			ret = FileUtil.readString(ClassLoaderUtil
					.getResourceFile("/testmsg.txt"));
		} catch (IOException e) {
			e.printStackTrace();
		}

		return ret;
	}
	/**
	 * 将违章结果适配成老的数据结构
	 * @param violations
	 * @return
	 */
	// {"error_code":0,"reason":"Success","result":{"city":"AH_HuaiNan","hphm":"皖D62601","hpzl":"02","province":"AH"}}
	public final static JSONObject convertToOld(final String vioRes) {
		final JSONObject newVioObj = JSON.parseObject(vioRes);
		final JSONObject resObj = new JSONObject();
		resObj.put("error_code", newVioObj.getIntValue("returncode"));
		resObj.put("reason","Success");
		final JSONObject result = new JSONObject();
		JSONObject newResult = newVioObj.getJSONObject("result");
		JSONArray citysArr = newResult.getJSONArray("citys");
		
//		result.put("city","AH_HuaiNan");
//		result.put("hphm", "皖D62601");
		// 号牌种类，02小型车
		result.put("hpzl", "02");
//		result.put("province", "AH");
		
		if(null!=citysArr&&citysArr.size()>0) {
			final JSONArray wzArr = new JSONArray();
			// 循环添加城市（每个城市可能有多个违章)
			final Iterator<Object> citysIter = citysArr.iterator();
			while(citysIter.hasNext()) {
				JSONObject currentCity = (JSONObject) citysIter.next();
				String cityid = currentCity.getString("cityid");
				String cityname = currentCity.getString("cityname");
				String timestamp = currentCity.getString("timestamp");
				
				JSONArray violationdata = currentCity.getJSONArray("violationdata");
				for(int i=0;i<violationdata.size();i++) {
					JSONObject vio = violationdata.getJSONObject(i);
					JSONObject wzObj = new JSONObject();
					wzObj.put("date", vio.getString("time"));
					// 违章地点
					wzObj.put("area", vio.getString("location"));
					// 违章行为
					wzObj.put("act", vio.getString("content"));
					// 违章代码，仅供参考
					//wzObj.put("code", vio.getString("recordid"));
					wzObj.put("fen", vio.getString("score"));
					wzObj.put("money", vio.getString("pay"));
					// 是否处理，处理状态1：已处理0：未处理
					wzObj.put("handled", vio.getString("processstatus"));
					wzObj.put("PayNo", vio.getString("recordid"));
					wzObj.put("longitude", vio.getString("Lat"));
					wzObj.put("latitude", vio.getString("Lng"));
					wzArr.add(wzObj);
				}
			}
			
			result.put("lists", wzArr);
		}
		
		resObj.put("result", result);
		
		return resObj;
	}
	
	public static void main(String[] args) throws IOException {
		// System.out.println(queryAllCities());
		// Map<String,String> params = new HashMap<String,String>();
		// params.put("platform_id", "17");
		// params.put("cityid", "340400");
		// params.put("cip", "122.114.123.94");
		// params.put("platenum", "皖DWX311");
		// params.put("enginenumber", "");
		// params.put("framenumber", "566718");
		// params.put("lng", null);
		// params.put("lat", null);
		// System.out.println(queryViolations(params));
		// System.out.println(queryCityIdByName("合肥"));

		System.out.println(mockData());
	}

	

}
